package com.github.live.plugins.base;

import com.alibaba.fastjson.JSONReader;
import com.github.live.util.LogFactory;
import com.github.livebase.bean.ChannelGroup;
import com.github.livebase.plugins.PluginContext;
import com.github.livebase.util.FileUtil;
import com.github.livebase.util.LiveContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ChannelsRegister
 * @description:
 * @author: biao532
 * @create: 2023-12-29 20:37
 * @Version 1.0
 **/
public class ChannelsRegister implements com.github.livebase.plugins.ChannelsRegister {

    @Override
    public List<ChannelGroup> register(LiveContext liveContext, PluginContext context) {
        // /storage/emulated/0/Android/data/com.github.live/files/channels.json

        try(InputStream inputStream = readTargetStream(liveContext)) {//new FileInputStream(file)) {
            if (inputStream == null) {
                return null;
            }
            List<ChannelGroup> cgs = new ArrayList<>();
            JSONReader reader = new JSONReader(new InputStreamReader(inputStream));
            reader.startArray();
            while (reader.hasNext()) {
                cgs.add(reader.readObject(ChannelGroup.class));
            }
            reader.endArray();
            LogFactory.info(ChannelsRegister.class, "从json文件 中读取到 {} 个频道组", cgs.size());
            return cgs;
        } catch (Exception e) {
            LogFactory.warn(ChannelsRegister.class, e, "json文件 解析失败");
        }
        return null;
    }
    private InputStream readTargetStream(LiveContext liveContext) throws FileNotFoundException {
        File file = new File(liveContext.getExternalFilesDir(""), "channels.link");
        try {
            file = FileUtil.link(file, liveContext);
        } catch (IOException e) {
            LogFactory.info(ChannelsRegister.class, e, ".link 文件获取失败");
            return defaultFileInputStream(liveContext);
        }
        if (!file.exists()) {
            LogFactory.info(ChannelsRegister.class, "路径 {} 不存在", file.getAbsolutePath());
            return defaultFileInputStream(liveContext);
        }
        return new FileInputStream(file);
    }
    private InputStream defaultFileInputStream(LiveContext liveContext) throws FileNotFoundException {
        File file = new File(liveContext.getExternalFilesDir(""), "channels.json");
        if (!file.exists()) {
            LogFactory.info(ChannelsRegister.class, "路径 {} 不存在", file.getAbsolutePath());
            return null;
        }
        return new FileInputStream(file);
    }
}
